﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon;

public class NPCController : MotionController 
{
	public float radiusOfOperation;
	public float maxEngagementRadius;
	public float minTimeBetweenMoves = 5;
	public float maxTimeBetweenMoves = 20;
	[HideInInspector]public NPCSpawn spawn;
	public override void GoTo(Vector3 position)
	{	
		speed = walkSpeed;
		following = false;
		destination = position;
		attacker.Relax();
		followTarget = null;
		minDistance = defaultMinDist;
		Idle();
	}
	public override void Update()
	{	
		if (agent.speed != speed)
		{
			agent.speed = speed;
		}
		if (following)
		{	
			if (followTarget == null)
			{
				GoTo(transform.position);
			} else
			{	
				if (GameFunctions.PlanarDistanceBetween(spawn.position,followTarget.transform.position)>maxEngagementRadius)
				{
					GoToRandom();
				}else
				{
					if (DistanceToFollowTarget() > minDistance)
					{
						agent.destination = closestPointToFollowTarget;
					} else
					{	
						agent.destination = this.transform.position;
					}
				}
			}
		} else
		{
			if(agent != null && destination != agent.destination)
			{
				agent.destination = destination;
			}
		}
	}
	void Idle()
	{
		float timeToWait = Random.Range(minTimeBetweenMoves,maxTimeBetweenMoves);
		StartCoroutine(WaitThenMove(timeToWait));
	}
	IEnumerator WaitThenMove(float time)
	{	float time1 = Time.time;
		yield return new WaitForSecondsRealtime(time);
		float time2 = Time.time - time1;
		if (!attacker.attacking && !following)
		{
			GoToRandom();
		}
	}
	void GoToRandom()
	{	
		Vector3 offset = Vector3.zero;
		if (radiusOfOperation>0)
		{
		float theta = Random.Range(0,2*Mathf.PI);
		float r = Random.Range(0,radiusOfOperation);
		offset = new Vector3(r*Mathf.Cos(theta),0,r*Mathf.Sin(theta));
		}
		GoTo(spawn.position + offset);
	}
	public override void StopAttacking()
	{		
		RunToRandom();
	}
	void RunToRandom()
	{
		GoToRandom();
		speed = runSpeed;
	}
	public override void Follow(Collider target)
	{	
		attacker.Relax();
		following = true;
		minDistance = defaultMinDist;
		followTarget = target;
		followTargetID = PhotonView.Get(target.transform.root).viewID;
	}
	public override void Attack(LifeController lc)
	{	
		if (lifeController.isDead || lc.isDead)
		{
			
		}else
		{	
			speed = runSpeed;
			following = true;
			followTarget = lc.col;
			followTargetID = PhotonView.Get(lc.transform.root).viewID;
			minDistance = attacker.gear.weapon.attackRange - attackDistanceBuffer;
			attacker.Target (lc);
		}

	}
	public override void LookAt(Vector3 targetPosition)
	{	
		
		Vector3 pos2d = new Vector3(transform.position.x,1,transform.position.z);
		Vector3 target2d = new Vector3(targetPosition.x,1,targetPosition.z);
		transform.rotation = Quaternion.LookRotation(target2d-pos2d,new Vector3(0,1,0));
		if (lrps != null)
		{
			lrps.SendPosition();
		}
	}
	

}
